const service = require('egg').Service;

class MenusService extends service {
  async userMenus() {
    const { ctx, app } = this;
    let data = await ctx.model.Users.findAll({
			include: [
				{
					model: ctx.model.Roles,
					include: [
						{
							model: ctx.model.Menus,
							exclude: ['created_at', 'updated_at'],
						},
					],
				},
			],
			where: {
				id: ctx.currentRequestData.userInfo.id,
			},
			raw:false
		})
		// 如果没有则直接返回空数组
    if (data.length === 0) {
      return [];
    }
    data = data[0].roles;
		// 去重
    const arr = [];
    data.forEach((e, i) => {
      e.menus.forEach((ee, ii) => {
        ee.__roles = {
          id: e.id,
          name: e.name,
        };
        arr.push(ee);
      });
    });
    data = app.lodash.uniqWith(arr, (a, b) => a.id === b.id);
    data = data.sort((a, b) => b.sort - a.sort);
    return data;
  }
}

module.exports = MenusService;